<?php

namespace Cours\QuizzBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Cours\QuizzBundle\Entity\Reponse;

class QuizzEleveController extends Controller
{
    
    
    public function indexAction(){
        
        $user = $this->container->get('security.context')->getToken()->getUser();
        $idPromo = $user->getPromotion();

        $em=$this->getDoctrine()->getManager();
        $qb=$em->createQueryBuilder();
        
        $nots=$qb->add('select', 'r')
            ->add('from', 'CoursQuizzBundle:Reponse r ')
            ->addSelect('c')
            ->leftJoin("r.Choix","c")
            ->addSelect('q')
            ->leftJoin("c.question","q")
            ->leftJoin("q.quizz","quizz")
            ->addSelect('quizz')
            ->where("r.iduser=".$this->container->get('security.context')->getToken()->getUser()->getId())
            ->orderby("quizz.id")
            ->getQuery()->getResult();
        
        $t=0;
        $oldquizz=0;
        $dejaQuizz=null;
        $lesnots=array();

        foreach($nots as $n){
            if($oldquizz!=$n->getChoix()->getQuestion()->getQuizz()->getId()){
                $t++;
                $lesnots[$t]=$n->getChoix()->getQuestion()->getQuizz()->getId();

                $note=0;
                $nbPoints=0;
                if($n->getSel()){
                    $nbPoints=$n->getChoix()->getPoints();
                    if($n->getChoix()->getPoints()>0){
                        $note=$n->getChoix()->getPoints();
                    }else{
                        $note=-$n->getChoix()->getQuestion()->getDecrementation();
                    }
                }
                $dejaQuizz[$t]["correction"]=array("note"=>$note,"note20"=>0,"nbpoints"=>$nbPoints);
                $dejaQuizz[$t]["quizz"]=$n->getChoix()->getQuestion()->getQuizz();


                $oldquizz=$n->getChoix()->getQuestion()->getQuizz()->getId();
            }else{
                $note=0;
                $nbPoints=0;
                if($n->getSel()){
                    $nbPoints=$n->getChoix()->getPoints(); 
                    if($nbPoints>0){
                        $note=$nbPoints;
                    }else{
                        $note=-$n->getChoix()->getQuestion()->getDecrementation();
                    }
                }
                $dejaQuizz[$t]["correction"]["note"]+=$note;
                $dejaQuizz[$t]["correction"]["nbpoints"]+=$nbPoints;
                if($dejaQuizz[$t]["correction"]["nbpoints"]>0){
                    $dejaQuizz[$t]["correction"]["note20"]=($dejaQuizz[$t]["correction"]["note"]/$dejaQuizz[$t]["correction"]["nbpoints"])*20;
                }
            }
        }
        if(count($dejaQuizz)>0){
            foreach ($dejaQuizz as $d => $v) {
                if($v["correction"]["note"]<0){
                    $dejaQuizz[$d]["correction"]["note"]=0;
                }
                if($v["correction"]["note20"]<0){
                    $dejaQuizz[$d]["correction"]["note20"]=0;
                }
            }
        }
        if(empty($idPromo)){
            $this->setFlash("error","Aucune promo ne vous est associée, contactez votre professeur");
        } else {
            if(count($lesnots)>0){
                $qb=$em->createQueryBuilder();
                $lesQuizz = $qb->add('select', 'q')
                        ->from('CoursQuizzBundle:Quizz','q')
                        ->where($qb->expr()->andx(
                            $qb->expr()->eq('q.promotion',$idPromo->getId()),
                            $qb->expr()->eq('q.active',1),
                            $qb->expr()->notIn('q.id', $lesnots)
                            )
                        )
                        ->getQuery()->getResult();
            }else {
                $qb=$em->createQueryBuilder();
                $lesQuizz = $qb->add('select', 'q')
                        ->from('CoursQuizzBundle:Quizz','q')
                        ->where($qb->expr()->andx(
                            $qb->expr()->eq('q.promotion',$idPromo->getId()),
                            $qb->expr()->eq('q.active',1)
                            )
                        )
                        ->getQuery()->getResult();

            }
        return $this->render('CoursQuizzBundle:Quizz:readAllEleve.html.twig', array('lesQuizz' => $lesQuizz,"dejaQuizz"=>$dejaQuizz));
        }   
    }
    
    public function readAllEleveAction($idUser){

        $em=$this->getDoctrine()->getManager();
        $qb=$em->createQueryBuilder();
        
        $nots=$qb->add('select', 'r')
            ->add('from', 'CoursQuizzBundle:Reponse r ')
            ->addSelect('c')
            ->leftJoin("r.Choix","c")
            ->addSelect('q')
            ->leftJoin("c.question","q")
            ->leftJoin("q.quizz","quizz")
            ->addSelect('quizz')
            ->where("r.iduser=".$idUser)
            ->orderby("quizz.id")
            ->getQuery()->getResult();
        
        $t=0;
        $oldquizz=0;
        $dejaQuizz=null;

        foreach($nots as $n){
            if($oldquizz!=$n->getChoix()->getQuestion()->getQuizz()->getId()){
                $t++;
                $lesnots[$t]=$n->getChoix()->getQuestion()->getQuizz()->getId();

                $note=0;
                $nbPoints=0;
                if($n->getSel()){
                    $nbPoints=$n->getChoix()->getPoints();
                    if($n->getChoix()->getPoints()>0){
                        $note=$n->getChoix()->getPoints();
                    }else{
                        $note=-$n->getChoix()->getQuestion()->getDecrementation();
                    }
                }
                $dejaQuizz[$t]["correction"]=array("note"=>$note,"note20"=>0,"nbpoints"=>$nbPoints);
                $dejaQuizz[$t]["quizz"]=$n->getChoix()->getQuestion()->getQuizz();


                $oldquizz=$n->getChoix()->getQuestion()->getQuizz()->getId();
            }else{
                $note=0;
                $nbPoints=0;
                if($n->getSel()){
                    $nbPoints=$n->getChoix()->getPoints(); 
                    if($nbPoints>0){
                        $note=$nbPoints;
                    }else{
                        $note=-$n->getChoix()->getQuestion()->getDecrementation();
                    }
                }
                $dejaQuizz[$t]["correction"]["note"]+=$note;
                $dejaQuizz[$t]["correction"]["nbpoints"]+=$nbPoints;
                if($dejaQuizz[$t]["correction"]["nbpoints"]>0){
                    $dejaQuizz[$t]["correction"]["note20"]=($dejaQuizz[$t]["correction"]["note"]/$dejaQuizz[$t]["correction"]["nbpoints"])*20;
                }
            }
        }
        if(count($dejaQuizz)>0){
            foreach ($dejaQuizz as $d => $v) {
                if($v["correction"]["note"]<0){
                    $dejaQuizz[$d]["correction"]["note"]=0;
                }
                if($v["correction"]["note20"]<0){
                    $dejaQuizz[$d]["correction"]["note20"]=0;
                }
            }
        }

        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('CoursUserBundle:User')->findById($idUser)[0];
        
        return $this->render('CoursQuizzBundle:Quizz:readAllEleveFromProf.html.twig', array("dejaQuizz"=>$dejaQuizz, "leuser"=>$user));   
    }
    
    
    public function readEleveAction($idUser,$idQuizz){
        $em = $this->getDoctrine()->getManager();

            $qb=$em->createQueryBuilder();
            $r=$qb->add('select', 'r')
                ->add('from', 'CoursQuizzBundle:Reponse r ')
                ->addSelect('c')
                ->leftJoin("r.Choix","c")
                ->addSelect('q')
                ->leftJoin("c.question","q")
                ->addSelect('quizz')
                ->leftJoin("q.quizz","quizz")
                ->orderBy("q.question")
                ->where($qb->expr()->andx(
                        $qb->expr()->eq('quizz.id',"$idQuizz"),
                        $qb->expr()->eq('r.iduser',$idUser)
                        )
                    )
                ->getQuery()->getResult();

                $t=0;
                $t2=0;
                foreach ($r as $c) {
                    $reponse[$c->getChoix()->getquestion()->getId()][$t2]=$c;
                    if(!isset($lesquizzfaits) || !isset($lesquizzfaits[$c->getChoix()->getquestion()->getId()])){
                        
                        $quizz=$c->getChoix()->getquestion()->getquizz();
                        $question[$t]=$c->getChoix()->getquestion();

                        $lesquizzfaits[$c->getChoix()->getquestion()->getId()]="fait";
                        $t++;
                    }
                    $t2++;
                }
                $a=array('quizz' => $quizz,'question'=>$question,"reponse"=>$reponse,"leuser"=>$r[0]->getIdUser());

                return $this->render('CoursQuizzBundle:Quizz:readEleveFromProf.html.twig', $a);
    }

    public function readAction($id){
        
        if(isset($id)){

            $em = $this->getDoctrine()->getManager();

            $qb=$em->createQueryBuilder();
            $r=$qb->add('select', 'r')
                ->add('from', 'CoursQuizzBundle:Reponse r ')
                ->addSelect('c')
                ->leftJoin("r.Choix","c")
                ->addSelect('q')
                ->leftJoin("c.question","q")
                ->addSelect('quizz')
                ->leftJoin("q.quizz","quizz")
                ->orderBy("q.question")
                ->where($qb->expr()->andx(
                        $qb->expr()->eq('quizz.id',"$id"),
                        $qb->expr()->eq('r.iduser',$this->container->get('security.context')->getToken()->getUser()->getId())
                        )
                    )
                ->getQuery()->getResult();

            if(count($r)==0){

                $em = $this->getDoctrine()->getManager();
                $tab=$em->createQueryBuilder()
                    ->add('select', 'c')
                    ->add('from', 'CoursQuizzBundle:Choix c ')
                    ->addSelect('q')
                    ->leftJoin("c.question","q")
                    ->addSelect('quizz')
                    ->leftJoin("q.quizz","quizz")
                    ->where("quizz.id=".$id)
                    ->getQuery()->getResult();

                shuffle($tab);

                $user = $this->container->get('security.context')->getToken()->getUser();
                $idPromo = $user->getPromotion();

                if($idPromo->getId()==$tab[0]->getQuestion()->getQuizz()->getPromotion()->getId()){

                    $t=0;
                    $t2=0;
                    foreach ($tab as $c) {
                        $tabChoix[$c->getquestion()->getId()][$t2]=$c;
                        if(!isset($lesquizzfaits) || !isset($lesquizzfaits[$c->getquestion()->getId()])){
                            
                            $quizz=$c->getquestion()->getquizz();
                            $question[$t]=$c->getquestion();

                            $lesquizzfaits[$c->getquestion()->getId()]="fait";
                            $t++;
                        }
                        $t2++;
                    }

        /*            
                    Faire gaffe à ce genre de requete, c'est beaucoup trop long et fait planter la page

                    $quizz = $em->getRepository('CoursQuizzBundle:Quizz')->find($id);
                    $question = $em->getRepository('CoursQuizzBundle:Question')->findByquizz($quizz);

                    $c=$em->getRepository('CoursQuizzBundle:Choix');
                    $tabChoix=array();
                    foreach ($question as $q) {
                        $v =$c->findByquestion($q->getId());
                        if(isset($v) && !empty($v)){
                            $tabChoix[$q->getId()]=$v;    
                        }
                        unset($v);
                    }
        */
                    $a=array('quizz' => $quizz,'question'=>$question,"choix"=>$tabChoix);

                    return $this->render('CoursQuizzBundle:Quizz:readEleve.html.twig', $a);
                } else {
                    $this->setFlash("error","Vous n'etes pas autorisé a acceder à ce quizz");
                    return $this->redirect($this->generateUrl('home_eleve'));
                }
             } else {
                $t=0;
                $t2=0;
                foreach ($r as $c) {
                    $reponse[$c->getChoix()->getquestion()->getId()][$t2]=$c;
                    if(!isset($lesquizzfaits) || !isset($lesquizzfaits[$c->getChoix()->getquestion()->getId()])){
                        
                        $quizz=$c->getChoix()->getquestion()->getquizz();
                        $question[$t]=$c->getChoix()->getquestion();

                        $lesquizzfaits[$c->getChoix()->getquestion()->getId()]="fait";
                        $t++;
                    }
                    $t2++;
                }

                $a=array('quizz' => $quizz,'question'=>$question,"reponse"=>$reponse);

                return $this->render('CoursQuizzBundle:Quizz:readEleve.html.twig', $a);
            }
        } else {

        }
    }
    
    public function checkQuizzAction($quizzId){
        $em = $this->getDoctrine()->getManager();

        $qb=$em->createQueryBuilder();
        $r=$qb->add('select', 'r')
            ->add('from', 'CoursQuizzBundle:Reponse r ')
            ->addSelect('c')
            ->leftJoin("r.Choix","c")
            ->addSelect('q')
            ->leftJoin("c.question","q")
            ->addSelect('quizz')
            ->leftJoin("q.quizz","quizz")
            ->orderBy("q.question")
            ->where($qb->expr()->andx(
                    $qb->expr()->eq('quizz.id',"$quizzId"),
                    $qb->expr()->eq('r.iduser',$this->container->get('security.context')->getToken()->getUser()->getId())
                    )
                )
            ->getQuery()->getResult();

        if(count($r)==0){
            if(isset($_POST)){
                $em = $this->getDoctrine()->getManager();
                $lesquestions=$em->getRepository('CoursQuizzBundle:Question')->findByquizz($quizzId);

                foreach ($lesquestions as $question) {
                    $question_id=$question->getId();

                    $LesChoix=$this->getDoctrine()->getManager()->createQueryBuilder()
                        ->add('select', 'c')
                        ->add('from', 'CoursQuizzBundle:Choix c ')
                        ->addSelect('q')
                        ->leftJoin("c.question","q")
                        ->where("q.id=".$question_id)
                        ->getQuery()->getResult();

                    $points=0;
                    $quizz=$quizzId;
                    if(isset($LesChoix) && count($LesChoix)>0){
                        foreach ($LesChoix as $c) {
                                $r = new Reponse();
                                $r->setChoix($c);
                                $r->setIdUser($this->container->get('security.context')->getToken()->getUser());

                                $tab["id"]=$c->getId();
                                echo $c->getId().'<br>';

                            if(isset($_POST["form"]) && isset($_POST["form"][$question_id]) && isset($_POST["form"][$question_id][$c->getId()]) && $c->getPoints()>0){
                                $r->setSel(true);
                                echo $c->getLibelle().'<br>';
                            } else if(isset($_POST["form"]) && isset($_POST["form"][$question_id]) && isset($_POST["form"][$question_id][$c->getId()]) && $c->getPoints()==0){
                                echo $c->getLibelle().'<br>';
                                $r->setSel(true);
                            }else {
                                $r->setSel(false);
                            }
                            $em->persist($r);
                        }
                        $em->flush();
                    }
                }
              //      return $this->render('CoursQuizzBundle:Questions:blank.html.twig',array());
                return $this->redirect($this->generateUrl('readQuizzEleve',array("id"=>$quizz)));
            }
        }
        else {
            $this->setFlash("error","Ce quizz a déjà été corrigé, Tricheur !!!!!");
            /// Rajout : Mail Nom + Prénom du Tricheur !!
            return $this->redirect($this->generateUrl('home_eleve'));
        }
    }
    
    /**
     * @param string $action
     * @param string $value
     */
    protected function setFlash($action, $value)
    {
        $this->container->get('session')->getFlashBag()->set($action, $value);
    }
}